import { isExist, isExistEmail } from "@/api/register";
import type { FormRules } from "element-plus";
import { reactive } from "vue";
import type { RegisterType } from "./interface";
const getRules = (ruleForm: RegisterType) => {
	const affirmPassword = () => ruleForm.password === ruleForm.affirmPassword;

	return reactive<FormRules>({
		userName: [
			{ required: true, message: "用户名不能为空", trigger: "blur" },
			{ min: 2, max: 10, message: "用户名必须在2-10个字符之间", trigger: "blur" },
			{ pattern: /^[A-Za-z][A-Za-z\d]+$/, message: "用户名必须由数字和字母组成，并以字母开头", trigger: "blur" },
			{
				asyncValidator(rule, value, callback) {
					isExist(ruleForm.userName)
						.then(() => {
							callback();
						})
						.catch(err => {
							callback(new Error(err.message));
						});
				},
				trigger: "blur"
			}
		],
		password: [
			{ required: true, message: "密码不能为空", trigger: "blur" },
			{ min: 8, max: 16, message: "密码必须由8-16个字符组成", trigger: ["blur", "change"] },
			{ pattern: /^[^\u4E00-\u9FFF]+$/, message: "密码必须非中文汉字组成,且不能包含空格", trigger: ["blur", "change"] }
		],
		affirmPassword: [
			{
				required: true,
				message: "确认密码不能为空",
				trigger: "blur"
			},
			{
				validator: affirmPassword,
				message: "两次输入的密码不一致",
				trigger: ["change", "blue"]
			}
		],
		email: [
			{
				required: true,
				message: "邮箱不能为空",
				trigger: "blur"
			},
			{
				type: "email",
				message: "请输入正确格式的邮箱地址",
				trigger: "blur"
			},
			{
				asyncValidator(rule, value, callback) {
					isExistEmail(ruleForm.email)
						.then(() => {
							callback();
						})
						.catch(err => {
							callback(new Error(err.message));
						});
				},
				trigger: "blur"
			}
		],
		emailKey: [
			{
				required: true,
				message: "验证码不能为空",
				trigger: "blur"
			},
			{
				len: 6,
				message: "请输入6位邮箱验证码",
				trigger: "blur"
			}
		],
		nickName: [
			{
				required: true,
				message: "昵称不能为空",
				trigger: "blur"
			},
			{
				min: 2,
				max: 10,
				message: "昵称必须由2-10位组成",
				trigger: "blur"
			},

			{
				pattern: /^[-_!@#$%^&*a-zA-Z0-9\u4e00-\u9fa5]+$/,
				message: "昵称必须由数字,字母,中文或-_!@#$%^&*组成",
				trigger: "blur"
			}
		]
	});
};
export default getRules;
